# core/adaptive_runner.py
import subprocess
import json
from typing import Optional
from aigc_integration import CozeAssistant, DEEPSEEKAssistant, DashscopeAssistant
from config.settings import Settings  # 导入配置


class AdaptiveTestRunner:
    def __init__(self, coze_assistant: Optional[CozeAssistant] = None, 
                 deepseek_assistant: Optional[DEEPSEEKAssistant] = None,
                 dashscope_assistant: Optional[DashscopeAssistant] = None):
        # 根据配置选择使用哪个助手
        self.aigc_provider = Settings.AIGC_PROVIDER.lower()
        
        if self.aigc_provider == "coze":
            self.assistant = coze_assistant or CozeAssistant()
        elif self.aigc_provider == "deepseek":
            self.assistant = deepseek_assistant or DEEPSEEKAssistant()
        elif self.aigc_provider == "dashscope":
            self.assistant = dashscope_assistant or DashscopeAssistant()
        else:
            raise ValueError(f"Unsupported AIGC provider: {Settings.AIGC_PROVIDER}")
        
        self.results_file = "test_results.json"

    def run_tests(self, test_path: str = "tests",
                  adaptive: bool = True) -> dict:
        """执行测试并收集结果"""
        cmd = f"pytest {test_path} --json-report --json-report-file={self.results_file}"
        result = subprocess.run(cmd, shell=True, capture_output=True, text=True)

        # 读取测试结果
        with open(self.results_file) as f:
            test_results = json.load(f)

        if adaptive:
            return self.adaptive_testing(test_results)
        return test_results

    def adaptive_testing(self, test_results: dict) -> dict:
        """根据测试结果进行自适应测试"""
        summary = test_results.get("summary", {})
        failed_tests = [t for t in test_results.get("tests", []) if t.get("outcome") == "failed"]

        # 根据使用的AIGC平台分析失败并生成新测试
        new_tests = []
        for test in failed_tests:
            # 修改为使用统一的接口
            analysis = self.assistant.analyze_failure(
                test.get("call", {}).get("crash", {}).get("message", ""),
                test.get("call", {}).get("crash", {}).get("traceback", "")
            )

            if analysis.get("improved_code"):
                # 保存改进的测试
                with open(f"tests/improved_{test['nodeid'].replace('/', '_')}.py", "w") as f:
                    f.write(analysis["improved_code"])
                new_tests.append(analysis["improved_code"])

            # 生成相关边界测试
            if "boundary" in analysis.get("fix_suggestion", "").lower():
                new_test = self.generate_boundary_test(test)
                new_tests.append(new_test)

        # 执行新生成的测试
        if new_tests:
            print(f"Executing {len(new_tests)} new adaptive tests")
            return self.run_tests("tests/improved_*.py", adaptive=False)

        return test_results

    def generate_boundary_test(self, failed_test: dict) -> str:
        """生成边界测试用例"""
        prompt = f"""
        基于失败的测试，生成边界测试用例:
        失败测试: {failed_test['nodeid']}
        失败原因: {failed_test.get('call', {}).get('crash', {}).get('message', '')}

        要求:
        1. 测试边界条件
        2. 包含极端值
        3. 使用pytest格式
        """
        # 修改为使用统一的生成接口
        return self.assistant.generate(prompt)
